#pragma once 

#include<iostream>
#include<sys/time.h>
#include<unistd.h>
#include<poll.h>
#include"Sock.hpp"
#include "log.hpp"

using namespace std;

static const int fd_num_max = 64;
static const uint16_t defaultport = 8080;
int defaultfd = -1;
int non_event = 0;
class PollServer
{
public:
    PollServer(uint16_t port = defaultport):_port(port)
    {
        for(int i = 0;i<fd_num_max;i++)
        {
            _event_fds[i].fd = defaultfd;
            _event_fds[i].events = non_event;
            _event_fds[i].revents = non_event;
        }
    }

    bool Init()
    {
        int listen_sock = _listensock.Socket();
        _listensock.Bind(listen_sock, _port);
        _listensock.Listen(listen_sock);

        return true;
    }

    void Accepter()
    {
        //连接的事件就绪了
        std::string clientip;
        uint16_t clientport = 0;
        int sock = _listensock.Accept(_listensock.Fd(), &clientip, &clientport);  //会不会阻塞在这里？不会,因为_listensock.Fd()的状态已经改变，说明有连接过来了
        if(sock < 0) return;
        logMessage(NORMAL, "accept success, %s : %d, sock fd: %d", clientip.c_str(), clientport, sock);

        //sock -> fd_array[]
        int pos = 1;
        for(;pos<fd_num_max;pos++)   //第二个循环
        {
            if(_event_fds[pos].fd!=defaultfd) continue;
            else break;
        }
        if(pos == fd_num_max)
        {
            logMessage(NORMAL, "server if full, close %d now!", sock);
            close(sock);
        }
        else    //如果可以连接了，那么将文件描述符进行监视
        {
            // fd_array[pos] = sock;
            _event_fds[pos].fd = sock;
            _event_fds[pos].events = POLLIN;
            _event_fds[pos].revents = non_event;
            PrintFd();
            //TODO
        }
    }

    void Recver(int fd, int pos)
    {
        //demo
        char buffer[1024];
        ssize_t n = read(fd, buffer, sizeof(buffer)-1);
        if(n>0)
        {
            buffer[n] = 0;
            cout<<"get a message: "<<buffer<<endl;
        }
        else if(n == 0)
        {
            logMessage(NORMAL, "client quit, me too, close fd is :%d ",fd);
            close(fd);
            _event_fds[pos].fd = defaultfd;
        }
        else     //读出错，就将该文件描述符关闭，并且辅助数组置为默认
        {
            logMessage(WARNING, "recv error: fd is : %d", fd);
            close(fd);
            _event_fds[pos].fd = defaultfd;
        }
    }

    void Dispatcher()
    {
        for(int i = 0;i<fd_num_max;i++)  //这是第三个for循环
        {
            int fd = _event_fds[i].fd;
            if(fd == defaultfd)
                continue;
            if(_event_fds[i].revents & POLLIN)    //如果读事件就绪,返回出来的参数放在revents里面
            {
                if(fd == _listensock.Fd())
                {
                    Accepter();  //连接管理器
                }
                else //non listenfd
                {
                    Recver(fd, i);    //本文就是读事件                    
                }
            }
        }
    }

    void Start()
    {
        _event_fds[0].fd= _listensock.Fd();
        _event_fds[0].events = POLLIN;
        int timeout = 3000;  //3s
        for(;;)    
        {

            int n = poll(_event_fds, fd_num_max, timeout);
            PrintFd();
            switch(n)
            {
                case 0:
                    cout<<"time out...."<<endl;
                    break;
                case -1:
                    cerr<<"poll error"<<endl;
                    break;
                default:
                    //有事件就绪了
                    cout<<"get a new link!!! "<<endl;
                    Dispatcher();  //就绪的事件和fd你怎么知道只有一个呢？
                    break;
            }
        }
    }

    void PrintFd()
    {
        cout<<" online fd list: ";
        for(int i = 0;i<fd_num_max;i++)
        {
            if(_event_fds[i].fd==defaultfd) continue;
            cout<<_event_fds[i].fd<< " ";
        }
        cout<<endl;
    }
    ~PollServer()
    {
        _listensock.Close();
    }

private:
    Sock _listensock;
    uint16_t _port;

    struct pollfd _event_fds[fd_num_max];  //数组，用户推荐的！

    //struct pollfd* _event_fds;

};